package cn.me.alphamq.broker.netty.cluster;

import cn.me.alphamq.common.entity.req.StartSyncReq;
import cn.me.alphamq.common.enumeration.EventCodeEnum;
import cn.me.alphamq.common.event.EventBus;
import cn.me.alphamq.common.remote.NettyClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * broker 主从同步中从节点的客户端
 *
 * @author f
 */
public class SlaveSyncClient {

    private static final Logger log = LoggerFactory.getLogger(SlaveSyncClient.class);

    /**
     * 连接到主 broker 节点的 netty 客户端
     */
    private NettyClient masterBrokerClient;

    /**
     * 初始化从节点与主节点之间的连接
     *
     * @param masterBrokerAddress 主节点的地址
     */
    public void initConnection(String masterBrokerAddress) {
        masterBrokerClient = new NettyClient(masterBrokerAddress);
        masterBrokerClient.initConnection("slave-broker-client", new SlaveSyncHandler(new EventBus("slave-sync-task")));
        masterBrokerClient.sendMsgSync(EventCodeEnum.START_SYNC_REQ, new StartSyncReq());
        log.info("master's connected successfully..");
    }

    /**
     * 当发生主从切换时，将此 从节点 与 主节点 连接的客户端清理掉
     */
    public void clean() {
        masterBrokerClient = null;
    }
}
